/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package batchjob;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jonesbr
 */
public class MonthlyRunner {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        run();
    }

    /**
     * Process a set of files.
     */
    private static void run() {
        // get access to the files that we want to process.
        File inputDirectory = new File("input");
        // list all of the files in the input directory.
        File[] allFiles = inputDirectory.listFiles();
        
        // iterate over all of the files.
        for (File file : allFiles) {
            try {
                // print the file name that we are processing.
                System.out.println(file.getAbsolutePath());
                Scanner thisScanner = new Scanner(file);
                String data = thisScanner.nextLine();
                System.out.println("Data: " + data);
                // get the filename from the file.
                String fileName = file.getName();
                // where is the underscore located in the string?
                int underscoreIndex = fileName.indexOf("_");
                // find out what file type we're dealing with by using substring.
                String fileType = fileName.substring(0, underscoreIndex);
                // ask the factory method for a class that handles this file type.
                IMonthlyItem monthlyItem = createMonthlyItem(fileType);
                // Command pattern: tell the class that implements MonthlyItem to process the given data.
                monthlyItem.process(data);
                                
                System.out.println("Processed: " + monthlyItem);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(MonthlyRunner.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(MonthlyRunner.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    /**
     * A facory method to create MonthlyItems
     * @param type
     * @return 
     */
    private static IMonthlyItem createMonthlyItem(String type) throws Exception {
        // Use refection to create an object based on a name of a class, where that name is in a String
        IMonthlyItem monthlyItem = (IMonthlyItem) Class.forName("batchjob."+type).newInstance();
        return monthlyItem;
    }
    
    
}
